package com.ugood.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密或者解密操作
 * @author lijiawei
 *
 */
public class EncodeUtils {
	
	public static final String EMPTY = "NULL";
	
	public static final int OFFSET = 5;
	
	/**
	 * 字符串加密
	 * @param str
	 * @return
	 */
	public static String encode(String str) {
		if(str == null) {
			return encode(EMPTY);
		}
		char[] cs = str.toCharArray();
		for(int index = 0; index < cs.length; index ++) {
			cs[index] = (char)(cs[index] + index * index * OFFSET);
		}
		cs[cs.length - 1] = (char)(cs[0] + cs[cs.length - 1]);
		return new String(cs);
	}
	
	/**
	 * 字符串解密
	 * @param str
	 * @return
	 */
	public static String decode(String str) {
		if(str == null) {
			return decode(EMPTY);
		}
		char[] cs = str.toCharArray();
		cs[cs.length - 1] = (char)(cs[cs.length - 1] - cs[0]);
		for(int index = 0; index < cs.length; index ++) {
			cs[index] = (char)(cs[index] - index * index * OFFSET);
		}
		return new String(cs);
	}
	
	public static String sha1(String data) throws NoSuchAlgorithmException {  
        MessageDigest md = MessageDigest.getInstance("SHA1");  
        md.update(data.getBytes());  
        StringBuffer buf = new StringBuffer();  
        byte[] bits = md.digest();  
        for(int i=0;i<bits.length;i++){  
            int a = bits[i];  
            if(a<0) a+=256;  
            if(a<16) buf.append("0");  
            buf.append(Integer.toHexString(a));  
        }  
        return buf.toString();  
    }  
	
}
